<template>
  <div>
    <Card>
      <div slot="title">
        <Button type="success" @click="addCarousel">添加</Button>
      </div>

      <Table :data="listData" type="index" :columns="listColumns" stripe></Table>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: right;">
          <Page :total="total" :current="current" @on-change="changePage"></Page>
        </div>
      </div>
    </Card>
    <Modal title="轮播图编辑" v-model="onEdit" @on-ok="saveCarousel">
      <Form :model="carData" :label-width="60">
        <FormItem label="标题">
          <Input v-model="carData.title"></Input>
        </FormItem>
        <FormItem label="图片">
          <div>
            <div class="poster-upload" v-if="hasPoster">
              <img :src="carData.image.imageBase">
              <div class="poster-cover">
                <Icon type="ios-eye-outline" size="25" @click.native="showImage(carData.image)"></Icon>
                <Icon type="ios-trash-outline" size="25" @click.native="removePoster()"></Icon>
              </div>
            </div>
          </div>
          <Upload ref="upload" v-show="!hasPoster"
                  :show-upload-list="false" :on-success="handleSuccess"
                  :format="['jpg','jpeg','png']" :max-size="2048" type="drag"
                  :on-exceeded-size="handleMaxSize"  :on-format-error="handleFormatError"
                  action="http://localhost:8080/api/file/upload" style="display: inline-block;width:200px;">
            <div style="width: 200px;height: 100px;line-height:115px;">
              <Icon type="camera" size="30"></Icon>
            </div>
          </Upload>
        </FormItem>
        <FormItem label="链接">
          <Input v-model="carData.url"></Input>
        </FormItem>
        <FormItem label="排序">
          <Input v-model="carData.seq" number></Input>
        </FormItem>
        <FormItem label="状态">
          <i-switch v-model="carData.isActive">
            <span slot="open">开</span>
            <span slot="close">关</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
    <Modal title="查看图片" v-model="visible">
      <img :src="imageBase" v-if="visible" style="width: 100%">
    </Modal>
  </div>
</template>

<script>
  export default {
    name: "carousel",
    data() {
      return {
        hasPoster: false,
        onEdit: false,
        visible: false,
        carData: {},
        carNode: {
          title: '',
          imageId: '',
          image: {},
          url: '',
          seq: 0,
          isActive: false
        },
        imageBase: '',
        limit: 0,
        page: 0,
        current: 1,
        total: 100,
        imageIds: [],
        imageList: [],
        listData: [],
        listColumns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: "标题",
            key: "title",
            width: 180
          },
          {
            title: "图片",
            key: 'image',
            width: 200,
            align: 'center',
            render: (h, params) => {
              if (this.imageList.length > 0) {
                const image = this.imageList.find(e => e.id === params.row.imageId);
                params.row.image = image;
                return h('div', {
                  attrs: {
                    class: 'list-img'
                  }
                }, [
                  h('img', {
                    attrs: {
                      src: image.imageBase
                    }
                  }),
                  h('div', {
                    attrs: {
                      class: 'list-img-cover'
                    }
                  }, [
                    h('Button', {
                      props: {
                        type: 'text',
                        icon: 'ios-eye-outline'
                      },
                      on: {
                        click: () => {
                          this.showImage(params.row.imageId);
                        }
                      }
                    })
                  ])]);
              }
              return;
            }
          },
          {
            title: "链接",
            key: "url"
          },
          {
            title: "排序",
            width: 80,
            key: "seq"
          },
          {
            title: "状态",
            width: 80,
            key: "isActive"
          },
          {
            title: "最新修改",
            key: "updatedOn",
            width: 200,
            render: (h, params) => {
              return h('span', new Date(params.row.updatedOn * 1000).toLocaleString())
            }
          },
          {
            title: "操作",
            key: "action",
            width: 250,
            align: "center",
            render: (h, params) => {
              return h("div", [
                h("Button",
                  {
                    props: {
                      icon: "edit",
                      type: "primary",
                      size: "small"
                    },
                    style: {
                      marginRight: "5px"
                    },
                    on: {
                      click: () => {
                        this.show(params.row);
                      }
                    }
                  },
                  "编辑"
                ),
                h(
                  "Poptip",
                  {
                    props: {
                      confirm: true,
                      width: 200,
                      title: "您确认删除这条内容吗？"
                    },
                    on: {
                      'on-ok': () => {
                        this.remove(params.row.id);
                      }
                    }
                  },
                  [h("Button", {
                    props: {
                      icon: "trash-a",
                      type: "error",
                      size: "small"
                    }
                  }, "删除")]
                )
              ]);
            }
          }
        ]
      };
    },
    methods: {
      init() {
        this.limit = 10;
        this.imageList = [];
        this.page = 0;
        this.current = 1;
        this.total = 100;
        this.mockListData(1);
      },
      loadImages(list) {
        list.forEach(e => this.imageIds.push(e.imageId));
        this.$axios({
          method: "post",
          url: "/api/image",
          data: {
            imageIds: this.imageIds
          }
        }).then((res) => {
          this.imageList = res.data;
        })
      },
      mockListData(init) {
        this.$axios({
          method: 'get',
          url: '/api/carousel',
          params: {
            page: this.page,
            limit: this.limit,
            init: init,
          }
        }).then((res) => {
          this.total = res.data.request.total;
          this.listData = res.data.result;
          this.loadImages(this.listData);
          this.$Notice.success({
            title: '加载成功!'
          });
        }).catch((error) => {
          this.$Notice.error({
            title: '加载失败!'
          });
          console.log(error);
        });
      },
      addCarousel() {
        this.onEdit = true;
        this.hasPoster = false;
        this.carData = Object.assign({}, this.carNode);
      },
      show(item) {
        this.onEdit = true;
        this.hasPoster = item.image !== undefined;
        this.carData = Object.assign({}, item);
      },
      remove(id) {
        this.$axios({
          method: 'delete',
          url: `/api/carousel/${id}`,
        }).then(res => {
          this.$Notice.success({
            title: '删除成功!'
          });
          this.init();
        }).catch(error => {
          this.$Notice.error({
            title: '删除失败!'
          });
          console.log(error);
        });
      },
      saveCarousel() {
        let url = '/api/carousel'+(this.carData.id===undefined?'':('/'+this.carData.id));
        this.$axios({
          method: 'post',
          url: url,
          data: {
            carData: {
              id: this.carData.id,
              title: this.carData.title,
              imageId: this.carData.imageId,
              url: this.carData.url,
              seq: this.carData.seq,
              active: this.carData.isActive
            }
          }
        }).then(res => {
          this.$Notice.success({
            title: '保存成功!'
          });
          this.init();
        }).catch(error => {
          this.$Notice.error({
            title: '保存失败!'
          });
        });
      },
      changePage(index) {
        // The simulated data is changed directly here, and the actual usage scenario should fetch the data from the server
        this.page = index;
        this.mockListData(1);
      },
      showImage(imageId) {
        this.imageBase = this.imageList.find(e => e.id === imageId).imageBase;
        this.visible = true;
      },
      removePoster() {
        this.hasPoster = false;
      },
      handleSuccess(res, file) {
        file.url = res.imageBase;
        file.name = res.imagePath;
        file.id = res.id;
        file.status = "finished";
        this.carData.imageId = res.id;
        this.carData.image = res;
        this.hasPoster = true;
      },
      handleFormatError(file) {
        this.$Notice.warning({
          title: "The file format is incorrect",
          desc:
          "File format of " +
          file.name +
          " is incorrect, please select jpg or png."
        });
      },
      handleMaxSize(file) {
        this.$Notice.warning({
          title: "Exceeding file size limit",
          desc: "File  " + file.name + " is too large, no more than 2M."
        });
      }
    },
    mounted() {
      this.init();
    }
  }
</script>

<style>
  .list-img {
    display: inline-block;
    width: 120px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  }

  .list-img img {
    width: 100%;
    height: 100%;
  }

  .list-img-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
  }

  .list-img:hover .list-img-cover {
    display: block;
  }

  .list-img-cover button i {
    color: #fff;
    font-size: 30px;
    cursor: pointer;
    margin: 0 2px;
  }

  .poster-upload {
    display: inline-block;
    width: 200px;
    height: 100px;
    text-align: center;
    line-height: 110px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    margin-right: 4px;
  }

  .poster-upload img {
    width: 100%;
    height: 100%;
  }

  .poster-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, 0.6);
  }

  .poster-upload:hover .poster-cover {
    display: block;
  }

  .poster-cover i {
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
